package controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import Client_Server.ClientConsole;
import static java.nio.file.StandardOpenOption.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Pattern;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.FontFormatting;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator;
import javax.sql.RowSet;
import javax.xml.namespace.QName;

import org.apache.poi.xssf.usermodel.XSSFSheet;
 
// TODO: Auto-generated Javadoc
/**
 * The Class ReportControl..Connects between the gui and the server. copies the reports
 *  to files saved in my documents.
 * create the customer report chart sorted by efficiency of the customer.
 */
public class ReportControl {

/** The table-for the Customer Report table. */
private static Object[][] table=null;
private String pc = null;


/**
 * Constructor for the report controller
 */
public ReportControl()
{}
	
/**
	 * Copy the deal report to a doc file in my documents.
	 *
	 * @param dataarr the dataarr
	 * @param rejections the rejections
	 * @param deal the deal
	 * @return the string(of the path of the file
	 */
	public String Create_DealReport(String[] dataarr,String rejections,String deal)
{
	
	String s ="Deal "+deal+"\n\n"+"Number of Customers Contacted:"+dataarr[0]+
			"\n"+"Number of Customer that Accepted the deal:"+dataarr[1]+
			"\nTime spent on call:"+dataarr[2]+"\n"+rejections;//-------text of the file
	String p=null;
	byte data[] = s.getBytes();//------covert the string to bytes
	try {
		byte b;
		 File f = null;//----------new file
		 
	    f =File.createTempFile("Deal", ".doc", new File("C:\\Users\\Public\\Documents\\"));
	    Path tempFile=f.toPath();//--------save file path
	    p="Deal Report" + " has been created:"+tempFile;
	    try (OutputStream out = new BufferedOutputStream(
	                 Files.newOutputStream(tempFile, APPEND))) {
	    		out.write(data, 0, data.length);//-----------copy the data to the file
	    		
	    } catch (IOException x) {
	    System.err.println(x);}
	
	} catch (IOException x) {
	    p="IOException:"+x;
	}
return p;
	 
}
	
/**
 * Sareches for the history of the deal- sends to ClientConsole ->server.
 * @param rid
 */

public void getdealhistory(String rid) {
	String arr[]=new String[10];
	 arr[0]="SumHistory";
	 arr[1]="historydb";
	 arr[2]=rid;
	 ClientConsole.HandleMessageFromGui(arr); 
}

	
	
	
/**
 * Create_ customer report-.
 */
public void Create_CustomerReport() {
	String[] arr = new String[3];
	arr[0]="CreateCustomerReport";
	arr[1]="customersdb";
	ClientConsole.HandleMessageFromGui(arr);
	
}

/**
 * create the chat for the customer report
 *
 * @param customers the customers
 * @return the object[][]
 */
public Object[][] create_chart(String[] customers) {
	Object[][]chart=new Object[150][3];
	int len=customers.length;
	len=(len-1)/4;
	int n=1;
	Object temp1,temp2,temp3;

	float num1,num3;
	float num2,num4;
	//----------------------create table matrix 
	for(int i=0;i<len;i++)
	{
		for(int j=0;j<3;j++)
		{
		
			if(j==2)//-------------calculate percent of efficiency for each customer
			{
				num1=Integer.parseInt(customers[n]);
				num2=Integer.parseInt(customers[n+1]);
				num3=(num1+num2);
				if(num3==0.0)
				{
					num3=0;
				}
				else{
					num3=num3/100;	
					num3=num1/num3;	
				}
			chart[i][j]=num3;
			n=n+2;
			}
			else
			{
				chart[i][j]=customers[n];
				n++;
			}
		}
		
	}
	//-----------sort table matrix(list of customers by percent of efficient
	for(int p=0;p<len;p++)
	{
		for(int k=0;k<len;k++)
		{
				num1=(float) chart[p][2];
				num2=(float) chart[k][2];
			if(num1>num2)
			{
				temp1=chart[p][1];
				chart[p][1]=chart[k][1];
				chart[k][1]=temp1;
			
				temp2=chart[p][0];
				chart[p][0]=chart[k][0];
				chart[k][0]=temp2;
			
				temp3=chart[p][2];
				chart[p][2]=chart[k][2];
				chart[k][2]=temp3;
			}
		}
	}
			settable(chart);
			return chart;
}


/**
 * Copy the Customer report to a excel file in my documents.
 * returns the path in witch the file is saved in.
 * @param amount the amount
 */
@SuppressWarnings("null")
public String CustomerReport_file(int amount)
{
    XSSFWorkbook workbook = new XSSFWorkbook();
    int num=2;
    String rows=null;
    
    String three;
    Object[][] chart=gettable();
    
    XSSFSheet sheet = workbook.createSheet("Customer Report");//-----------Create a blank sheet
      
    //------------This data needs to be written (Object[])
    Map<String, Object[]> data = new TreeMap<String, Object[]>();
    data.put("1", new Object[] {"Customer Id", "Customer name", "Percent of purchases"});
    for(int i=0;i<amount;i++)
    {
    rows=""+num;
    three=""+chart[i][2];

    data.put(rows, new Object[] {chart[i][0],chart[i][1],three});
    num++;
    }
     //-----------Iterate over data and write to sheet
    Set<String> keyset = data.keySet();
    int rownum = 0;
    for (String key : keyset)
    {
        Row row = sheet.createRow(rownum++);
        Object [] objArr = data.get(key);
        int cellnum = 0;
        for (Object obj : objArr)
        {
           Cell cell = row.createCell(cellnum++);
           if(obj instanceof String)
                cell.setCellValue((String)obj);
            else if(obj instanceof Integer)
                cell.setCellValue((Integer)obj);
        }
    }
    try
    {
        FileOutputStream out = new FileOutputStream(new File("C:\\Users\\Public\\Documents\\Customer_Report.xlsx"));
        workbook.write(out);
        out.close();
        pc="The Customer Efficency Report was created in"+"C:\\Users\\Public\\Documents\\Customer_Report.xlsx";
    }
    catch (Exception e)
    {
        e.printStackTrace();
        pc="The file was not created";
    }
    return pc;
}

/**
 * Sets the table.
 *
 * @param table1 the new table
 */
public static void settable(Object[][] table1)
{
	table=table1;
}

/**
 * Gets the table.
 *
 * @return the table
 */
public static Object[][] gettable()
{
	return table;
}


}
